﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Security.Permissions;

namespace JQuery.Net.UI
{
    public class ControlBuilder
        : System.Web.UI.ControlBuilder
    {
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public override Type GetChildControlType(string tagName, System.Collections.IDictionary attribs)
        {
            if (String.Compare(tagName, "rendertemplate", true) == 0)
            {
                return typeof(Template);
            }
            else if (String.Compare(tagName, "script", true) == 0)
            {
                return typeof(ClientScript);
            }
            else return null;
        }
    }

    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("Script")]
    [ParseChildren(true, "Script")]
    public class Template
        : Control
    {
        #region constructor
        public Template()
            : base()
        {
            HtmlTag = HtmlTextWriterTag.Script;
        }
        #endregion

        #region variables
        private string _script = null;
        #endregion

        #region properties
        protected HtmlTextWriterTag HtmlTag { get; set; }
        [PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty)]
        public string Script
        {
            get { return _script; }
            set { _script = value.Replace("\"", "\\\"").Trim(); }
        }
        [PersistenceMode(PersistenceMode.Attribute)]
        public String Type { get; set; }
        #endregion

        #region render
        protected override void Render(HtmlTextWriter writer)
        {
            
            writer.AddAttribute(HtmlTextWriterAttribute.Id, ID);
            writer.AddAttribute(HtmlTextWriterAttribute.Type, Type);
            /// render the opening element
            writer.RenderBeginTag(HtmlTag);
            /// render the body
            writer.Write(Script.Trim());
            /// render the closing element
            writer.RenderEndTag();
        }
        #endregion
    }
}
